package org.reos.ReParser;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

public class RTGenConfigReader {
	private ArrayList<ISection> sections = new ArrayList<ISection>();

	public ArrayList<ISection> populateConfigFromFile(String pathToInputFile) {
        ArrayList<String> fileData = new ArrayList<String>();

		try {
			BufferedReader br = new BufferedReader(new FileReader(new File(pathToInputFile)));
			String str;
			while ((str = br.readLine()) != null) {
				fileData.add(str);
			}
			br.close();
		} catch (FileNotFoundException e) {
			System.out.println("Could not find the file: " + pathToInputFile);
			e.printStackTrace();
            return null;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
            return null;
		}

        parseFileData(fileData);
        return sections;
	}

    private void parseFileData(ArrayList<String> fileData) {
		ISection currentSection = null;
		String currentSectionName = null;

		for (String line : fileData) {
			String str = getPureString(line);
			if (str.equals("")) {
				continue;
			}

            String tempSectionName = null;
			if ((tempSectionName = Section.parseSectionName(str)) != null) {
                currentSection = null;
				currentSectionName = tempSectionName;
                for (ISection section : sections) {
					if (section.getSectionName().equals(currentSectionName)) {
						currentSection = section;
						break;
					}
				}
				if (currentSection == null) {
					currentSection = Section.getInstance(currentSectionName);
					sections.add(currentSection);
				}
			} else {
				if (currentSection == null) {
					System.out.println("Error line " + ": One of the supported sections expected, the line is ignored");
					continue;
				}
				currentSection.setSectionAttribute(str);
            }
//			System.out.println(str);
		}
	}

	private String getPureString(String str) {
		String[] tmp = str.split("##");
		return ((tmp.length == 0) ? "" : tmp[0].trim());
	}
	
}
